package com.zhengtoudai.injector.module;

import android.content.Context;
import android.view.LayoutInflater;

import com.squareup.otto.Bus;
import com.zhengtoudai.base.App;
import com.zhengtoudai.http.CacheControlInterceptor;
import com.zhengtoudai.util.Tool;

import java.io.File;
import java.util.concurrent.TimeUnit;

import javax.inject.Singleton;

import dagger.Module;
import dagger.Provides;
import okhttp3.Cache;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;

/**
 * Created by Administrator on 2016/8/23 0023.
 */

@Module
public class AppModule {
    private final Context mContext;

    public AppModule(Context mContext) {
        this.mContext = mContext;
    }

    @Singleton
    @Provides
    public Context ProvideAppContext() {
        return mContext.getApplicationContext();
    }

    @Singleton
    @Provides
    public Bus ProvideBusEvent() {
        return new Bus();
    }

    @Singleton
    @Provides
    public OkHttpClient ProvideOkHttpClient() {

        Cache cache = new Cache(new File(App.getContext().getCacheDir(), "ztdCache"),
                1024 * 1024 * 100);
        // 云端响应头拦截器，用来配置缓存策略
        CacheControlInterceptor cacheControlInterceptor = new CacheControlInterceptor();
        //日志拦截器
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                Tool.showLog("okHttp",message);
            }
        });
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient mOkHttpClient = new OkHttpClient.Builder()
                .cache(cache)   //缓存
                .addNetworkInterceptor(cacheControlInterceptor) //缓存与添加公共请求头
                .addInterceptor(cacheControlInterceptor)
                .addInterceptor(logging)    //打印日志
                .retryOnConnectionFailure(true)//失败重连
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .build();
        return mOkHttpClient;
    }

    @Singleton
    @Provides
    public LayoutInflater provideLayoutInflater() {
        return (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }


}
